package com.combetter.changxing.viewmodel;

import android.app.Application;
import android.support.annotation.NonNull;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.combetter.changxing.MyApp;
import com.combetter.changxing.R;
import com.combetter.changxing.model.MessageModel;
import com.combetter.changxing.db.entity.Record;
import com.combetter.changxing.net.service.APIService;
import com.combetter.changxing.util.AppManager;
import com.combetter.changxing.util.LogUtil;
import com.combetter.changxing.util.ToastUtils;
import com.combetter.changxing.viewmodel.base.BaseRecyclerViewModel;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * 类名  消息viewModel
 * 作者  tlfx: Sean.guo
 * 日期  2018/10/16 15:44
 */
public class MessageViewModel extends BaseRecyclerViewModel {
    public List<Record> messages = new ArrayList<>();

    public MessageViewModel(@NonNull Application application) {
        super(application, R.layout.item_message);
    }

    public void back(View view) {
        AppManager.finishCurrentActivity();
    }

    /**
     * 获取吸烟记录
     */
    public void getMsgList(SmartRefreshLayout refreshLayout) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid", MyApp.getInstance().getUserInfo().getUid());
        map.put("pagenum", "1");
        map.put("pagesize", "9999");
        mHttpRequest.createService(APIService.class)
                .getMsgList(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnError(throwable -> refreshLayout.finishRefresh())
                .subscribe(httpResult -> {
                    refreshLayout.finishRefresh();
                    if (httpResult.getCode() == 200) {
                        LogUtil.e("---:: "+httpResult.getData());
                        JSONObject jsonObject = new JSONObject(new Gson().toJson(httpResult.getData()));
                        String resultData = jsonObject.getString("resultData");
                        messages.clear();
                        messages = new Gson().fromJson(resultData, new TypeToken<List<MessageModel>>() {
                        }.getType());
                        clear();
                        items.addAll(messages);
                    } else {
                        ToastUtils.error(httpResult.getMsg());
                    }
                });
    }
}
